package adventure.commands.admin;

import adventure.*;
import adventure.commands.*;
import colour.ColourUtil;
import player.*;

/**
 *
 * @author Michael Hanns
 *
 */
public class AdminDemote extends AbstractCommand {

    public AdminDemote(Adventure a) {
        super(a, new String[]{"ADMINDEMOTE"});
    }

    @Override
    public String validateAndExecute(Player p, String[] args) {
        if (p.isSuperAdmin()) {
            if (args.length == 2) {
                return demoteFromAdmin(p, args[1]);
            } else {
                return "Demote who to a standard user?\nSyntax: admindemote <player name>";
            }
        } else {
            return "Command not recognised.";
        }
    }

    private String demoteFromAdmin(Player p, String target) {
        Player targetPlayer = players.getOnlinePlayer(target);

        if (targetPlayer.getID() == p.getID()) {
            return "You cannot demote yourself!";
        }

        if (targetPlayer.getID() > 0) {
            if (targetPlayer.isSuperAdmin()) {
                return "You cannot demote another super administrator! This can only be done by modifying the player file and restarting the server.";
            } else if (!targetPlayer.isAdmin()) {
                return ColourUtil.colourise(targetPlayer.getAliveName(), ColourUtil.player) + " is not an administrator!";
            }

            ((PlayerEdit) targetPlayer).setAdmin(false);
            out.broadcastToPlayer(targetPlayer,
                    ColourUtil.colourise(p.getAliveName(), ColourUtil.player)
                    + ColourUtil.colourise(" has demoted you and removed your administration priviliges.", ColourUtil.white));

            players.savePlayers();
            return "You have demoted "
                    + ColourUtil.colourise(targetPlayer.getAliveName(), ColourUtil.player)
                    + " and removed their administration privilidges.";
        } else {
            targetPlayer = players.getOfflinePlayer(target);

            if (targetPlayer.getID() > 0) {
                if (targetPlayer.isSuperAdmin()) {
                    return "You cannot demote another super administrator! This can only be done by modifying the player file and restarting the server.";
                } else if (!targetPlayer.isAdmin()) {
                    return ColourUtil.colourise(targetPlayer.getAliveName(), ColourUtil.player) + " is not an administrator!";
                }

                ((PlayerEdit) targetPlayer).setAdmin(false);
                return "You have demoted "
                        + ColourUtil.colourise(targetPlayer.getAliveName(), ColourUtil.player)
                        + " and removed their administration privilidges.";
            } else {
                return "Player " + target + " does not exist!";
            }
        }
    }
}
